package com.rzt.cft.admin.config;

import com.rzt.cft.constant.ServiceStatus;
import com.rzt.cft.dto.ResponseData;
import com.rzt.cft.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName GlobalExceptionHandler
 * @Description: 全局异常处理
 * @Author zhong
 * @Date 2019/11/14 0014
 * @Version V1.0
 **/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    //处理自定义异常
    @ExceptionHandler(CustomException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //响应吗
    @ResponseBody
    public ResponseData handlerMyException(HttpServletRequest request, CustomException e) {
        log.error("BaseException [{}]", e.getMessage(), e);
        return new ResponseData() {{
            setCode(e.getServiceStatus().getCode());
            setMessage(e.getServiceStatus().getMessage());
        }};
    }

    //处理自定义异常
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //响应吗
    @ResponseBody
    public ResponseData handlerMyException(HttpServletRequest request, RuntimeException e) {
        log.error("BaseException [{}]", e.getMessage(), e);
        return new ResponseData() {{
            setCode(ServiceStatus.SERVICE_EXCEPTION.getCode());
            setMessage(ServiceStatus.SERVICE_EXCEPTION.getMessage());
        }};
    }

    //处理自定义异常
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //响应吗
    @ResponseBody
    public ResponseData handlerException(HttpServletRequest request, Exception e) {
        log.error("BaseException [{}]", e.getMessage(), e);
        return new ResponseData() {{
            setCode(ServiceStatus.SERVICE_EXCEPTION.getCode());
            setMessage(ServiceStatus.SERVICE_EXCEPTION.getMessage());
        }};
    }

}
